import { GetSearchSongs, GetSearchSongsSugList } from "apis/index";
import { showToast, navigateTo } from "utils/index";
const app = getApp();
Page({
  data: {
    navHeight: "",
    searchVal: "", //搜索关键词
    currPage: 1,
    hasNextPage: true,
    searchedList: [], //搜索结果
    sugList: [],
  },

  onLoad(options) {
    const { value } = options;
    const { menuButton, navBarHeight } = app.globalData.systemInfo;
    console.log("navBarHeight----------", navBarHeight);
    this.setData({
      searchVal: value.trim(),
      navBtnHeight: menuButton.height + "px",
      navBarHeight: navBarHeight + "px",
    });
    this.getSearchedList();
  },

  onShareAppMessage() {},
  //确认搜索的关键词时
  onSearch(e) {
    this.setData({
      currPage: 1,
      sugList: [],
      searchVal: e.detail,
    });
    this.getSearchedList();
  },
  //当输入搜索内容时
  onInput(e) {
    const value = e.detail;
    if (!value) {
      this.setData({
        sugList: [],
      });
      return;
    }
    GetSearchSongsSugList({ keywords: value, limit: 10 }).then((res) => {
      let list = res.songs || [];
      list = list.map((it) => {
        const html = it.name.replace(
          new RegExp(value, "g"),
          `<span style="color:red;">${value}</span>`
        );
        return {
          html,
          text: it.name,
        };
      });
      this.setData({
        sugList: list,
      });
    });
  },
  //清除搜索关键词
  onClear() {
    this.setData({
      sugList: [],
      searchedList: [],
    });
  },
  //获取搜索结果列表
  getSearchedList() {
    const { hasNextPage, currPage, searchedList, searchVal } = this.data;
    if (!searchVal) {
      showToast("请输入搜索内容");
      return;
    }
    if (currPage === 1 || hasNextPage) {
      GetSearchSongs({
        keywords: searchVal,
        limit: 15,
        offset: currPage - 1,
      }).then((res) => {
        const { songs, hasMore } = res;
        let newList = songs || [];
        newList = newList.map((item) => {
          item.singers = item.artists.map((it) => it.name).join(" - ");
          return item;
        });
        this.setData({
          searchedList:
            currPage === 1 ? newList : [...searchedList, ...newList],
          hasNextPage: hasMore,
        });
      });
    } else {
      showToast("没有更多了");
    }
  },
  onReachBottom() {
    const { searchedList, currPage } = this.data;
    if (searchedList.length) {
      this.setData({
        currPage: currPage + 1,
      });
      this.getSearchedList();
    }
  },
  //点击联想下拉项时
  onSugItem(e) {
    const { html, text } = e.detail;
    this.onSearch({ detail: text });
  },
});
